import { houselist1 } from '../api/house';
import { newhouselist } from '../api/newhouse';

const IndexModel = {
  namespace: 'index',

  state: {
    houselist: [],
    newhouselist:[]
  },

  effects: {
    *INIT(action, { call, put }) {
      const data = yield call(houselist1);
      const data1 = yield call(newhouselist);
      yield put({ type: 'GETLIST', payload: data.data.data });
      yield put({ type: 'newGETLIST', payload: data1.data.RECORDS });
    },
  },
  reducers: {

    GETLIST(state, { payload }) {
      state.houselist = payload;
      return { ...state };
    },
    newGETLIST(state, { payload }) {
      state.newhouselist = payload;
      return { ...state };
    },
    ADDHOUSE(state, { payload }) {
      state.houselist.unshift(payload)
      return { ...state };
    },
    BIAN(state, { payload }) {
      state.houselist.forEach((item,index)=>{
        if (item.id===payload.id) {
          state.houselist[index]=payload
        }
      })
      return { ...state };
    },

    SOU(state, { payload }) {
      state.houselist=state.houselist.filter((item) => {
        return item.title.includes(payload);
      });
      return { ...state };
    },
    NEWSOU(state, { payload }) {
      state.newhouselist=state.newhouselist.filter((item) => {
        return item.title.includes(payload);
      });
      return { ...state };
    },

    DEL(state, { payload }) {
      console.log(payload);
      state.houselist.forEach((item, index) => {
        if (item.id === payload.id) {
          state.houselist.splice(index, 1);
        }
      });
      state.houselist=[...state.houselist]
      return { ...state };
    },
    NEWDEL(state, { payload }) {
      console.log(payload);
      state.newhouselist.forEach((item, index) => {
        if (item.id === payload.id) {
          state.newhouselist.splice(index, 1);
        }
      });
      state.newhouselist=[...state.newhouselist]
      return { ...state };
    },
  },
  subscriptions: {
    init({ dispatch }) {
      dispatch({type:"INIT"})
    },
  },
};

export default IndexModel;
